<?php

/**
 * 商户登录
 * User: csyr
 * Date: 6/25/16
 * Time: 15:25
 */

namespace Home\Model;
use Think\Model;

class MerchantUserModel extends Model{

    /**
     * 编辑用户余额
     * @param $merchantId
     * @param $balance
     * @return bool
     */
    public function updateBalance($merchantId, $balance) {
        $merchantUser = $this->where(['merchant_id'=>$merchantId])->find();
        if ($merchantUser) {
            $currentBalance = $merchantUser['balance'];
            $balance = intval($currentBalance) + $balance;
            return $this->where(['merchant_id'=>$merchantId])->setField('balance', $balance);
        }
        return false;
    }

    public function has($data, $throwException = true) {
        if (is_numeric($data)) {
            $data = ['id' => $data];
        }

        if (!is_array($data)) {
            if ($throwException) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            return null;
        }

        $information = M('MerchantUser')->where($data)->find();

        if (!$information) {
            $throwException && BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
        }

        return $information;
    }

    /*********************************************************************
     * 功能描述：录入商户信息(注册)
     * 创建时间：2016-08-04
     *********************************************************************/
    public function saveMerchantUser($merchant)
    {
        //商户注册，商户信息表预留一条数据，给id值占个坑
        $data = array(
            "name"     => $merchant['name'],
            "status"   => 3,  //默认是待完善资料
            "add_time" => time()
        );
        $result = M('Merchant')->add($data);
        
        //录入商户登陆信息表
        if($result){
            unset($merchant['name']);
            $merchant['merchant_id'] = $result;
            $merchant['add_time'] = time();
            $merchant['password'] = get_enc_password($merchant['password']);
            $res = M('MerchantUser')->add($merchant);
        }
        if($res && $result){
            return true;
        }
        return false;
    }
}
